<template>
  <transition name="tj-notification-fade" @before-leave="onClose" @after-leave="$emit('destroy')">
    <div v-show="visible"
         class="tj-notification"
         :style="positionStyle"
         :id="id"
         @mouseenter="clearTimer"
         @mouseleave="startTimer"
         @click="onClick">
      <div class="tj-notification__group">
        <h2 class="tj-notification__title" v-text="title"></h2>
        <div class="tj-notification__content" v-show="message">
          <slot>
            <p v-text="message"></p>
          </slot>
        </div>
        <div class="tj-notification__closeBtn"
             @click.stop="close"
        >
          <span class="material-icons">close</span>
        </div>
      </div>

    </div>
  </transition>

</template>

<script>
import {computed, defineComponent, onMounted, ref} from "vue";

export default defineComponent({
  name: "blog-notification",
  props: {
    title: {
      type: String,
      default: '',
    },
    message: {
      type: [String, Object],
      default: '',
    },
    id: {type: String, default: '',},
    duration: {
      type: Number,
      default: 4500,
    },
    offset: {
      type: Number,
      default: 0,
    },
    position: {
      type: String,
      default: 'top',
    },

    onClick: {
      type: Function,
      default: () => void 0,
    },
    onClose: {
      type: Function,
      default: () => void 0,
    },
  },
  emits: ['destroy'],

  setup(props) {

    const visible = ref(false);
    let timer = null;

    function startTimer() {
      if (props.duration > 0) {
        timer = setTimeout(() => {
          if (visible.value) {
            close();
          }
        }, props.duration);
      }
    }

    function clearTimer() {
      clearTimeout(timer);
      timer = null;
    }

    function close() {
      visible.value = false
    }

    // lifecycle
    onMounted(() => {
      startTimer();
      visible.value = true;
    })

    // styles
    const verticalProperty = computed(() => {
      return props.position.startsWith('top') ? 'top' : 'bottom';
    })

    const positionStyle = computed(() => {
      return {
        [verticalProperty.value]: `${props.offset}px`,
      }
    })

    return {
      visible,
      positionStyle,

      startTimer,
      clearTimer,
      close,
    }
  },

});
</script>